﻿@*
    工艺添加/编辑页面
*@
@{
    var isEmbed = Context?.Request?.Query["embed"].ToString() == "1";
    Layout = isEmbed ? null : "_Layout";
    ViewData["Title"] = "工艺管理";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<style>
    /* 页面整体样式 */
    body {
        margin: 0;
        padding: 0;
        background: #f5f5f5;
        min-height: 100vh;
    }

    /* 主容器样式 */
    .main-container {
        width: 100%;
        min-height: 100vh;
        background: #f5f5f5;
        padding: 20px;
        box-sizing: border-box;
    }

    /* 表单卡片样式 */
    .form-card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        padding: 30px;
        margin-bottom: 20px;
    }

    /* 区域标题样式 */
    .section-title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        margin-bottom: 25px;
        padding-bottom: 15px;
        border-bottom: 2px solid #1e88e5;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 10px;
        color: #1e88e5;
        font-size: 20px;
    }

    /* 表单行样式 */
    .form-row {
        display: flex;
        gap: 40px;
        margin-bottom: 30px;
        flex-wrap: wrap;
    }

    .form-item {
        flex: 1;
        min-width: 320px;
    }

    .form-item.full-width {
        flex: 1 1 100%;
        min-width: 100%;
    }

    .form-item label {
        display: block;
        font-weight: 600;
        color: #333;
        margin-bottom: 10px;
        font-size: 15px;
    }

    .form-item label.required::after {
        content: " *";
        color: #f44336;
        font-weight: bold;
        font-size: 16px;
    }

    .form-item input,
    .form-item select,
    .form-item textarea {
        width: 100%;
        padding: 12px 15px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s ease;
        box-sizing: border-box;
        background-color: #fff;
    }

    .form-item input:focus,
    .form-item select:focus,
    .form-item textarea:focus {
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
        outline: none;
    }

    /* 下拉框特殊样式 */
    .form-select {
        cursor: pointer;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
        background-position: right 12px center;
        background-repeat: no-repeat;
        background-size: 16px;
        padding-right: 40px;
        appearance: none;
        -webkit-appearance: none;
        -moz-appearance: none;
    }

    .form-select:hover {
        border-color: #1e88e5;
    }

    .form-item textarea {
        resize: vertical;
        min-height: 80px;
    }

    /* 输入框和复选框组合样式 */
    .input-with-checkbox {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .input-with-checkbox input[type="text"] {
        flex: 1;
        margin-right: 0;
        transition: all 0.3s ease;
    }
    
    /* 工艺编号输入框样式 */
    .input-with-checkbox input[type="text"][readonly] {
        background-color: #f8f9fa;
        color: #6c757d;
        cursor: not-allowed;
        border-color: #e9ecef;
    }
    
    .input-with-checkbox input[type="text"]:not([readonly]) {
        background-color: white;
        color: #495057;
        cursor: text;
        border-color: #007bff;
    }

    /* 系统编号复选框样式 */
    .system-code-checkbox {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 5px 0;
        white-space: nowrap;
    }

    .system-code-checkbox input[type="checkbox"] {
        width: auto;
        margin: 0;
        transform: scale(1.1);
    }

    .system-code-checkbox label {
        font-size: 14px;
        color: #666;
        margin: 0;
        cursor: pointer;
    }
    
    /* 刷新编号按钮样式 */
    .btn-refresh {
        background: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 4px 8px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s ease;
        margin-left: 8px;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }
    
    .btn-refresh:hover {
        background: #0056b3;
        transform: scale(1.05);
    }
    
    .btn-refresh:active {
        transform: scale(0.95);
    }

    /* 状态单选按钮样式 */
    .status-radio {
        display: flex;
        align-items: center;
        gap: 20px;
        margin-top: 10px;
        padding: 5px 0;
    }

    .status-radio input[type="radio"] {
        width: auto;
        margin: 0;
        transform: scale(1.1);
    }

    .status-radio label {
        font-size: 14px;
        color: #333;
        margin: 0;
        cursor: pointer;
        margin-left: 5px;
    }

    .status-radio .radio-group {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    /* 工序表格样式 */
    .process-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    .process-table th,
    .process-table td {
        padding: 12px 8px;
        text-align: center;
        border: 1px solid #e0e0e0;
        vertical-align: middle;
    }

    .process-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #333;
    }

    .process-table td input[type="text"] {
        width: 90%;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 3px;
        font-size: 12px;
    }

    .process-table .checkbox-cell {
        width: 50px;
    }

    .process-table .operation-cell {
        width: 200px;
    }

    /* 操作链接样式 */
    .operation-link {
        display: inline-block;
        padding: 4px 8px;
        margin: 0 2px;
        text-decoration: none;
        border-radius: 3px;
        font-size: 12px;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .operation-link.primary {
        background: #1e88e5;
        color: white;
    }

    .operation-link.primary:hover {
        background: #1565c0;
        color: white;
    }

    .operation-link.danger {
        background: #f44336;
        color: white;
    }

    .operation-link.danger:hover {
        background: #d32f2f;
        color: white;
    }

    /* 按钮样式 */
    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
        margin-right: 10px;
    }

    .btn-primary {
        background: #1e88e5;
        color: white;
    }

    .btn-primary:hover {
        background: #1565c0;
        transform: translateY(-1px);
    }

    .btn-warning {
        background: #ff9800;
        color: white;
    }

    .btn-warning:hover {
        background: #f57c00;
        transform: translateY(-1px);
    }

    .btn-danger {
        background: #f44336;
        color: white;
    }

    .btn-danger:hover {
        background: #d32f2f;
        transform: translateY(-1px);
    }

    .btn-success {
        background: #4caf50;
        color: white;
    }

    .btn-success:hover {
        background: #388e3c;
        transform: translateY(-1px);
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }

    /* 操作按钮区域 */
    .action-buttons {
        margin-top: 30px;
        padding: 20px 0;
        text-align: center;
        border-top: 1px solid #e0e0e0;
        background: #fafafa;
        border-radius: 0 0 8px 8px;
    }

    .action-buttons .btn {
        margin: 0 10px;
        padding: 12px 30px;
        font-size: 14px;
    }



    /* Layui表格样式优化 */
    .layui-table-view {
        margin-top: 20px;
    }

    .layui-form-item {
        margin-bottom: 15px;
    }

    .layui-input-inline {
        width: 180px;
    }

    .layui-form-label {
        width: 80px;
    }

    /* 响应式设计 */
    @@media (max-width: 768px) {
        .form-row {
            flex-direction: column;
            gap: 20px;
        }
        
        .form-item {
            min-width: auto;
        }
        
        .action-buttons .btn {
            display: block;
            width: 100%;
            margin: 10px 0;
        }
    }
    
    /* 工序选择对话框内容隐藏样式 */
    #processDialogContent {
        position: absolute !important;
        top: -9999px !important;
        left: -9999px !important;
        visibility: hidden !important;
        z-index: -1 !important;
        display: none !important;
    }
    
    /* 当对话框打开时，内容应该可见 */
    .layui-layer-content #processDialogContent {
        position: static !important;
        top: auto !important;
        left: auto !important;
        visibility: visible !important;
        z-index: auto !important;
        display: block !important;
    }
    
    /* 工序选择对话框美化样式 */
    .layui-layer-content #processDialogContent {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    }
    
    /* 搜索区域美化 - 卡片式布局 */
    .layui-layer-content #processDialogContent .layui-form {
        background: white;
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        border: 1px solid #e9ecef;
        position: relative;
        overflow: hidden;
    }
    
    /* 卡片顶部装饰条 */
    .layui-layer-content #processDialogContent .layui-form::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #007bff, #28a745, #fd7e14);
    }
    
    .layui-layer-content #processDialogContent .layui-form-item {
        margin-bottom: 0;
        display: flex;
        align-items: center;
        gap: 20px;
        flex-wrap: nowrap;
        justify-content: space-between;
    }
    
    .layui-layer-content #processDialogContent .layui-form-label {
        color: #495057;
        font-weight: 600;
        font-size: 14px;
        margin-bottom: 0;
        min-width: 85px;
        white-space: nowrap;
        display: flex;
        align-items: center;
        gap: 8px;
        margin-right: 25px;
    }
    
    .layui-layer-content #processDialogContent .layui-input-inline {
        margin-bottom: 0;
        flex: 1;
        max-width: 200px;
        margin-left: 15px;
    }
    
    .layui-layer-content #processDialogContent .layui-input {
        border: 2px solid #e9ecef;
        border-radius: 8px;
        padding: 10px 15px;
        transition: all 0.3s ease;
        font-size: 14px;
        width: 100%;
        background: #f8f9fa;
    }
    
    .layui-layer-content #processDialogContent .layui-input:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        outline: none;
        background: white;
        transform: translateY(-1px);
    }
    
    /* 按钮组美化 */
    .layui-layer-content #processDialogContent .button-group {
        display: flex;
        gap: 12px;
        align-items: center;
    }
    
    .layui-layer-content #processDialogContent .layui-btn {
        border-radius: 8px;
        padding: 10px 18px;
        font-weight: 500;
        transition: all 0.3s ease;
        border: none;
        font-size: 14px;
        min-width: 80px;
        display: flex;
        align-items: center;
        gap: 6px;
        justify-content: center;
    }
    
    .layui-layer-content #processDialogContent .layui-btn-normal {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
        color: white;
    }
    
    .layui-layer-content #processDialogContent .layui-btn-normal:hover {
        background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0, 123, 255, 0.3);
    }
    
    .layui-layer-content #processDialogContent .layui-btn-warm {
        background: linear-gradient(135deg, #fd7e14 0%, #e55a00 100%);
        color: white;
    }
    
    .layui-layer-content #processDialogContent .layui-btn-warm:hover {
        background: linear-gradient(135deg, #e55a00 0%, #cc4a00 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(253, 126, 20, 0.3);
    }
    
    /* 表格美化 */
    .layui-layer-content #processDialogContent .layui-table {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        border: 1px solid #e9ecef;
    }
    
    .layui-layer-content #processDialogContent .layui-table thead tr {
        background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    }
    
    .layui-layer-content #processDialogContent .layui-table thead th {
        color: white;
        font-weight: 600;
        padding: 15px 12px;
        border: none;
        font-size: 14px;
        text-align: center;
    }
    
    .layui-layer-content #processDialogContent .layui-table tbody tr {
        transition: all 0.2s ease;
    }
    
    .layui-layer-content #processDialogContent .layui-table tbody tr:hover {
        background-color: #f8f9fa;
        transform: scale(1.01);
    }
    
    .layui-layer-content #processDialogContent .layui-table tbody td {
        padding: 12px 8px;
        border-bottom: 1px solid #e9ecef;
        text-align: center;
        font-size: 13px;
        color: #495057;
    }
    
    /* 表格内容美化 */
    .layui-layer-content #processDialogContent .process-code {
        font-family: 'Courier New', monospace;
        font-weight: 600;
        color: #007bff;
        background: rgba(0, 123, 255, 0.1);
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
    }
    
    .layui-layer-content #processDialogContent .process-name {
        font-weight: 600;
        color: #495057;
    }
    
    .layui-layer-content #processDialogContent .process-type {
        color: #6c757d;
        font-size: 12px;
    }
    
    .layui-layer-content #processDialogContent .process-responsible {
        color: #28a745;
        font-weight: 500;
    }
    
    .layui-layer-content #processDialogContent .process-dept {
        color: #6c757d;
        font-size: 12px;
    }
    
    .layui-layer-content #processDialogContent .process-note {
        color: #6c757d;
        font-size: 12px;
        font-style: italic;
    }
    
    /* 状态徽章美化 */
    .layui-layer-content #processDialogContent .status-badge {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        gap: 4px;
    }
    
    .layui-layer-content #processDialogContent .status-enabled {
        background: rgba(40, 167, 69, 0.1);
        color: #28a745;
        border: 1px solid rgba(40, 167, 69, 0.3);
    }
    
    .layui-layer-content #processDialogContent .status-disabled {
        background: rgba(220, 53, 69, 0.1);
        color: #dc3545;
        border: 1px solid rgba(220, 53, 69, 0.3);
    }
    
    /* 选择按钮美化 */
    .layui-layer-content #processDialogContent .select-btn {
        background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
        color: white;
        border-radius: 6px;
        padding: 6px 12px;
        font-size: 12px;
        transition: all 0.3s ease;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }
    
    .layui-layer-content #processDialogContent .select-btn:hover {
        background: linear-gradient(135deg, #1e7e34 0%, #155724 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
    }
    

    
    /* 表格容器美化 */
    .layui-layer-content #processDialogContent .table-container {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        border: 1px solid #e9ecef;
        margin-bottom: 20px;
    }
    
    .layui-layer-content #processDialogContent .table-header {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        padding: 15px 20px;
        border-bottom: 1px solid #e9ecef;
        font-size: 16px;
        color: #495057;
        display: flex;
        align-items: center;
    }
    
    /* 分页控件样式 - 强制单行布局 */
    .layui-layer-content #processDialogContent #demo-laypage-all {
        text-align: center;
        margin-top: 20px;
        background: white;
        padding: 15px;
        border-radius: 8px;
        border: 1px solid #e9ecef;
        overflow: hidden;
    }
    
    .layui-layer-content #processDialogContent .layui-laypage {
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 15px !important;
        flex-wrap: nowrap !important;
        width: 100% !important;
        white-space: nowrap !important;
        overflow-x: auto !important;
    }
    
    /* 分页元素样式 - 防止换行 */
    .layui-layer-content #processDialogContent .layui-laypage a,
    .layui-layer-content #processDialogContent .layui-laypage span {
        margin: 0 2px !important;
        padding: 6px 10px !important;
        border-radius: 4px !important;
        border: 1px solid #e9ecef !important;
        background: white !important;
        color: #495057 !important;
        text-decoration: none !important;
        transition: all 0.2s ease !important;
        white-space: nowrap !important;
        flex-shrink: 0 !important;
        min-width: auto !important;
        max-width: none !important;
    }
    
    .layui-layer-content #processDialogContent .layui-laypage a:hover {
        background: #f8f9fa !important;
        border-color: #007bff !important;
        color: #007bff !important;
    }
    
    .layui-layer-content #processDialogContent .layui-laypage .layui-laypage-curr {
        background: #007bff !important;
        color: white !important;
        border-color: #007bff !important;
        font-weight: 500 !important;
    }
    
    /* 输入框和下拉框样式 - 防止换行 */
    .layui-layer-content #processDialogContent .layui-laypage input,
    .layui-layer-content #processDialogContent .layui-laypage select {
        border: 1px solid #e9ecef !important;
        border-radius: 4px !important;
        padding: 4px 6px !important;
        background: white !important;
        color: #495057 !important;
        font-size: 13px !important;
        white-space: nowrap !important;
        flex-shrink: 0 !important;
        min-width: auto !important;
        max-width: none !important;
    }
    
    /* 页面跳转输入框特殊样式 - 缩小宽度 */
    .layui-layer-content #processDialogContent .layui-laypage .layui-laypage-skip input {
        width: 35px !important;
        text-align: center !important;
        padding: 4px 4px !important;
    }
    
    .layui-layer-content #processDialogContent .layui-laypage input:focus,
    .layui-layer-content #processDialogContent .layui-laypage select:focus {
        border-color: #007bff !important;
        outline: none !important;
        box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1) !important;
    }
    
    /* 确定按钮样式 - 防止换行 */
    .layui-layer-content #processDialogContent .layui-laypage button {
        background: #28a745 !important;
        color: white !important;
        border: none !important;
        border-radius: 4px !important;
        padding: 4px 12px !important;
        font-size: 13px !important;
        cursor: pointer !important;
        transition: all 0.2s ease !important;
        white-space: nowrap !important;
        flex-shrink: 0 !important;
        min-width: auto !important;
        max-width: none !important;
    }
    
    .layui-layer-content #processDialogContent .layui-laypage button:hover {
        background: #1e7e34 !important;
    }
    
    /* 强制所有分页相关元素不换行 */
    .layui-layer-content #processDialogContent .layui-laypage * {
        white-space: nowrap !important;
        flex-shrink: 0 !important;
    }
    
    /* 禁用状态的选择按钮样式 */
    .layui-layer-content #processDialogContent .layui-btn-disabled {
        background-color: #f5f5f5 !important;
        color: #999 !important;
        border-color: #e6e6e6 !important;
        cursor: not-allowed !important;
        opacity: 0.6 !important;
    }
    
    .layui-layer-content #processDialogContent .layui-btn-disabled:hover {
        background-color: #f5f5f5 !important;
        color: #999 !important;
        border-color: #e6e6e6 !important;
        transform: none !important;
        box-shadow: none !important;
    }
    
    /* 响应式优化 */
    @@media (max-width: 768px) {
        .layui-layer-content #processDialogContent .layui-form-item {
            flex-direction: column;
            align-items: stretch;
            gap: 15px;
        }
        
        .layui-layer-content #processDialogContent .layui-input-inline {
            width: 100%;
            max-width: none;
        }
        
        .layui-layer-content #processDialogContent .button-group {
            justify-content: center;
            width: 100%;
        }
        
        .layui-layer-content #processDialogContent .layui-btn {
            flex: 1;
            max-width: 120px;
        }
    }
    
    /* 中等屏幕优化 */
    @@media (max-width: 1200px) and (min-width: 769px) {
        .layui-layer-content #processDialogContent .layui-form-item {
            gap: 15px;
        }
        
        .layui-layer-content #processDialogContent .layui-input-inline {
            max-width: 180px;
        }
    }
    
    /* 加载状态样式已取消 */
    
    /* 编辑模式提示样式 */
    .edit-mode-notice {
        margin-bottom: 15px;
        padding: 10px;
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 4px;
        color: #856404;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    /* 工序备注输入框样式 */
    .process-note-input {
        width: 100%;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 12px;
    }
    
    .process-note-input:focus {
        border-color: #1e88e5;
        outline: none;
        box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.1);
    }
</style>

<div class="main-container">
            <form id="craftsForm" novalidate>
        <!-- 基础信息 -->
        <div class="form-card">
            <div class="section-title">
                <i class="layui-icon layui-icon-form"></i>
                基础信息
            </div>
            
            <!-- 第一行：工艺流程编号和工艺流程名称 -->
            <div class="form-row">
                <div class="form-item">
                    <label class="required">工艺流程编号</label>
                    <div class="input-with-checkbox">
                        <input type="text" id="craftsCode" name="craftsCode" value="CRA0001" readonly />
                        <div class="system-code-checkbox">
                            <input type="checkbox" id="isSystemCode" name="isSystemCode" checked onchange="toggleCraftsCodeInput()" />
                            <label for="isSystemCode">系统编号</label>
                            <button type="button" id="refreshCodeBtn" class="btn-refresh" onclick="generateCraftsCode()" title="重新生成编号">
                                <i class="layui-icon layui-icon-refresh"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="form-item">
                    <label class="required">工艺流程名称</label>
                    <input type="text" id="craftsName" name="craftsName" placeholder="请输入工艺流程名称" />
                </div>
            </div>
            
            <!-- 第二行：负责人和所属部门 -->
            <div class="form-row">
                <div class="form-item">
                    <label>负责人</label>
                    <select id="responsibilityName" name="responsibilityName" class="form-select">
                        <option value="">请选择负责人</option>
                        <option value="张伟">张伟</option>
                        <option value="李娜">李娜</option>
                        <option value="王强">王强</option>
                        <option value="赵敏">赵敏</option>
                        <option value="刘芳">刘芳</option>
                    </select>
                </div>
                
                <div class="form-item">
                    <label>所属部门</label>
                    <select id="department" name="department" class="form-select">
                        <option value="">请选择部门</option>
                        <option value="1">生产部</option>
                        <option value="2">质检部</option>
                        <option value="3">技术部</option>
                        <option value="4">采购部</option>
                        <option value="5">销售部</option>
                    </select>
                </div>
            </div>
            
            <!-- 第三行：状态 -->
            <div class="form-row">
                <div class="form-item">
                    <label>状态</label>
                    <div class="status-radio">
                        <input type="radio" id="craftsStatusEnabled" name="craftsStatus" value="0" checked />
                        <label for="craftsStatusEnabled">启用</label>
                        <input type="radio" id="craftsStatusDisabled" name="craftsStatus" value="1" />
                        <label for="craftsStatusDisabled">禁用</label>
                    </div>
                </div>
                
                <div class="form-item">
                    <!-- 空占位，保持布局平衡 -->
                </div>
            </div>
            
            <!-- 第四行：备注（全宽） -->
            <div class="form-row">
                <div class="form-item full-width">
                    <label>备注</label>
                    <textarea id="note" name="note" placeholder="请输入备注"></textarea>
                </div>
            </div>
        </div>

        <!-- 加工工序 -->
        <div class="form-card">
            <div class="section-title">
                <i class="layui-icon layui-icon-list"></i>
                加工工序
            </div>
            
                        <div style="margin-bottom: 20px;">
                <button type="button" class="btn btn-warning" onclick="removeProcess()">
                    <i class="layui-icon layui-icon-delete"></i>
                    移除
                </button>
                <button type="button" class="btn btn-primary" onclick="openProcessDialog()">
                    <i class="layui-icon layui-icon-add-1"></i>
                    添加工序
                </button>
            </div>
            
            <table class="process-table" id="processTable">
                <thead>
                    <tr>
                        <th class="checkbox-cell">
                            <input type="checkbox" id="selectAll" onclick="toggleSelectAll()" />
                        </th>
                        <th>序号</th>
                        <th>加工工序</th>
                        <th>工序编码</th>
                        <th>工序名称</th>
                        <th>负责人</th>
                        <th>所属部门</th>
                        <th>备注</th>
                        <th class="operation-cell">操作</th>
                    </tr>
                </thead>
                <tbody id="processTableBody">
                    <!-- 工序行将通过JavaScript动态生成 -->
                </tbody>
            </table>
        </div>



        <!-- 工序选择对话框内容 - 隐藏状态，仅用于对话框 -->
        <div id="processDialogContent" style="display: none; position: absolute; top: -9999px; left: -9999px; visibility: hidden; z-index: -1;">
            <!-- 搜索条件 -->
            <form class="layui-form" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">
                            <i class="layui-icon layui-icon-code" style="color: #007bff;"></i>
                            工序编号
                        </label>
                        <div class="layui-input-inline">
                            <input type="text" id="searchProcessCode" placeholder="请输入工序编号" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">
                            <i class="layui-icon layui-icon-edit" style="color: #007bff;"></i>
                            工序名称
                        </label>
                        <div class="layui-input-inline">
                            <input type="text" id="searchProcessName" placeholder="请输入工序名称" class="layui-input">
                        </div>
                    </div>
                    <div class="button-group">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="searchProcesses()">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="button" class="layui-btn layui-btn-warm" onclick="resetSearch()">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                    </div>
                </div>
            </form>
            
            <!-- 工序列表 -->
            <div class="table-container">
                <div class="table-header">
                    <i class="layui-icon layui-icon-list" style="margin-right: 8px; color: #6c757d;"></i>
                    <span style="font-weight: 600; color: #495057;">工序列表</span>
                </div>
                <table class="layui-table">
                    <thead>
                        <tr>
                            <th><i class="layui-icon layui-icon-code" style="margin-right: 5px;"></i>工序编号</th>
                            <th><i class="layui-icon layui-icon-edit" style="margin-right: 5px;"></i>工序名称</th>
                            <th><i class="layui-icon layui-icon-tabs" style="margin-right: 5px;"></i>工序类型</th>
                            <th><i class="layui-icon layui-icon-user" style="margin-right: 5px;"></i>负责人</th>
                            <th><i class="layui-icon layui-icon-ok-circle" style="margin-right: 5px;"></i>状态</th>
                            <th><i class="layui-icon layui-icon-home" style="margin-right: 5px;"></i>所属部门</th>
                            <th><i class="layui-icon layui-icon-note" style="margin-right: 5px;"></i>备注</th>
                            <th><i class="layui-icon layui-icon-util" style="margin-right: 5px;"></i>操作</th>
                        </tr>
                    </thead>
                    <tbody id="tb">
                        <!-- 工序数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            
            <!-- 分页控件 -->
            <div id="demo-laypage-all"></div>
        </div>



        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button type="button" class="btn btn-success" onclick="saveCrafts()">
                <i class="layui-icon layui-icon-ok"></i>
                保存
            </button>
            <button type="button" class="btn btn-warning" onclick="resetForm()">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
            <button type="button" class="btn btn-danger" onclick="goBack()">
                <i class="layui-icon layui-icon-return"></i>
                返回
            </button>

        </div>
    </form>
</div>

<script>
    // 全局变量
    var processCounter = 0;
    var processes = [];

    // 页面加载完成后执行
    $(function() {
        initLayui();
        
        // 验证页面元素
        console.log('页面加载完成，检查关键元素:');
        console.log('processTableBody存在:', $('#processTableBody').length > 0);
        console.log('processes数组初始状态:', processes);
        console.log('processCounter初始值:', processCounter);
        
        // 禁用所有表单的默认验证行为
        disableFormValidation();
        
        // 检查是否为编辑模式
        checkEditMode();
    });
    
    // 禁用表单验证
    function disableFormValidation() {
        // 禁用HTML5表单验证
        $('form').attr('novalidate', true);
        
        // 阻止表单提交时的默认验证
        $('form').on('submit', function(e) {
            e.preventDefault();
            return false;
        });
        
        // 阻止所有input的验证事件
        $('input, select, textarea').on('invalid', function(e) {
            e.preventDefault();
            return false;
        });
        
        console.log('表单验证已禁用');
    }

    // 初始化Layui
    function initLayui() {
        layui.use(['form', 'layer'], function() {
            var form = layui.form;
            var layer = layui.layer;
            
            // 禁用Layui的默认表单验证
            form.config.verify = {};
            
            console.log('Layui已初始化，表单验证已禁用');
        });
    }
    
    // 检查是否为编辑模式
    function checkEditMode() {
        var urlParams = new URLSearchParams(window.location.search);
        var craftsId = urlParams.get('id');
        
        console.log('URL参数解析结果:', craftsId);
        console.log('完整URL:', window.location.href);
        
        if (craftsId) {
            console.log('检测到编辑模式，工艺ID:', craftsId);
            console.log('工艺ID类型:', typeof craftsId);
            console.log('工艺ID值:', craftsId);
            
            // 设置为编辑模式
            setEditMode();
            
            // 尝试从sessionStorage获取工艺数据
            var sessionData = sessionStorage.getItem('editCraftsData');
            if (sessionData) {
                try {
                    var craftsData = JSON.parse(sessionData);
                    console.log('从sessionStorage获取到工艺数据:', craftsData);
                    
                    // 直接显示工艺详情
                    displayCraftsDetails(craftsData);
                    
                    // 加载工序列表 - 使用URL中的真实ID
                    loadProcessesList(craftsId);
                    
                    // 清除sessionStorage中的数据
                    sessionStorage.removeItem('editCraftsData');
                } catch (e) {
                    console.error('解析sessionStorage数据失败:', e);
                    // 如果解析失败，回退到API调用
                    loadCraftsDetails(craftsId);
                }
            } else {
                // 如果没有sessionStorage数据，调用API获取
                loadCraftsDetails(craftsId);
            }
        } else {
            console.log('新增模式，初始化工艺编号');
            // 新增模式，初始化工艺编号
            generateCraftsCode();
        }
    }
    
    // 设置编辑模式
    function setEditMode() {
        // 修改页面标题
        $('.section-title').first().html('<i class="layui-icon layui-icon-form"></i>编辑工艺');
        
        // 修改保存按钮文本
        $('.btn-success').html('<i class="layui-icon layui-icon-ok"></i>更新');
        
        // 编辑模式下不显示提示横幅
    }
    
    // 加载工艺详情
    function loadCraftsDetails(craftsId) {
        console.log('开始加载工艺详情，ID:', craftsId);
        
        // 调用API获取工艺详情
        $.ajax({
            url: 'http://localhost:5161/api/Process/CraftsQuery',
            dataType: 'json',
            type: 'get',
            data: {
                PageIndex: 1,
                PageSize: 1,
                id: craftsId
            },
            success: function(res) {
                console.log('工艺详情API响应:', res);
                
                if (res.code === 200 && res.data.list && res.data.list.length > 0) {
                    var craftsData = res.data.list[0];
                    displayCraftsDetails(craftsData);
                    // 加载工序列表
                    loadProcessesList(craftsId);
                } else {
                    showError('未找到工艺数据');
                }
            },
            error: function(xhr, status, error) {
                console.error('加载工艺详情失败:', error);
                showError('加载工艺详情失败，请重试');
            }
        });
    }
    
    // 显示工艺详情
    function displayCraftsDetails(craftsData) {
        console.log('开始显示工艺详情:', craftsData);
        
        // 填充基础信息
        $('#craftsCode').val(craftsData.craftsCode || '');
        $('#craftsName').val(craftsData.craftsName || '');
        $('#responsibilityName').val(craftsData.responsibilityName || '');
        $('#department').val(craftsData.departId || '');
        
        // 设置状态
        // 状态值映射：0=启用，1=禁用
        console.log('工艺状态值:', craftsData.craftsStatus, '类型:', typeof craftsData.craftsStatus);
        
        if (craftsData.craftsStatus === 0 || craftsData.craftsStatus === '0') {
            // 状态值为0时，选中"启用"
            $('#craftsStatusEnabled').prop('checked', true);
            console.log('设置状态为：启用');
        } else if (craftsData.craftsStatus === 1 || craftsData.craftsStatus === '1') {
            // 状态值为1时，选中"禁用"
            $('#craftsStatusDisabled').prop('checked', true);
            console.log('设置状态为：禁用');
        } else {
            // 默认状态或未知状态，选中"启用"
            $('#craftsStatusEnabled').prop('checked', true);
            console.log('默认设置状态为：启用');
        }
        
        // 设置备注
        $('#note').val(craftsData.note || '');
        
        // 禁用系统编号相关功能（编辑模式下不允许修改编号）
        $('#isSystemCode').prop('disabled', true);
        $('#refreshCodeBtn').prop('disabled', true);
        
        console.log('工艺详情显示完成');
    }
    
    // 加载工序列表
    function loadProcessesList(craftsId) {
        console.log('开始加载工序列表，工艺ID:', craftsId);
        console.log('URL中的工艺ID参数:', craftsId);
        
        // 显示加载状态
        $('#processTableBody').html('<tr><td colspan="9" style="text-align: center; color: #999; padding: 20px;">正在加载工序数据...</td></tr>');
        
        // 调用真实的API获取工序列表
        $.ajax({
            url: 'http://localhost:5161/api/Process/ProcessCratfs',
            type: 'GET',
            data: { 
                craftsId: craftsId  // 工艺数据的真实主键id（来自URL参数）
            },
            dataType: 'json',
            beforeSend: function() {
                console.log('发送AJAX请求，参数:', { craftsId: craftsId });
            },
            success: function(res) {
                console.log('工序列表API响应:', res);
                console.log('请求参数确认 - 工艺ID:', craftsId);
                
                if (res.code === 200 && res.data) {
                    // 成功获取数据，显示工序列表
                    displayProcessesList(res.data);
                } else {
                    // API返回错误或没有数据
                    console.warn('获取工序列表失败或没有数据:', res.message || '未知错误');
                    $('#processTableBody').empty();
                }
            },
            error: function(xhr, status, error) {
                console.error('获取工序列表失败:', error);
                console.error('HTTP状态:', xhr.status);
                console.error('响应文本:', xhr.responseText);
                console.error('请求参数 - 工艺ID:', craftsId);
                
                // 显示错误状态
                $('#processTableBody').html(`
                    <tr>
                        <td colspan="9" style="text-align: center; color: #dc3545; padding: 20px;">
                            <i class="layui-icon layui-icon-close-fill" style="font-size: 20px; margin-bottom: 10px;"></i>
                            <p>加载工序数据失败</p>
                            <p style="font-size: 12px; margin-top: 5px;">工艺ID: ${craftsId}</p>
                            <button class="btn btn-primary btn-sm" onclick="loadProcessesList('${craftsId}')">重试</button>
                        </td>
                    </tr>
                `);
            }
        });
    }
    
    // 显示工序列表
    function displayProcessesList(processesData) {
        console.log('开始显示工序列表，原始数据:', processesData);
        
        if (!processesData || processesData.length === 0) {
            // 编辑模式下不显示"暂无工序数据"提示，保持表格为空
            $('#processTableBody').empty();
            console.log('没有工序数据，表格已清空');
            return;
        }
        
        var tbody = $('#processTableBody');
        tbody.empty();
        
        processesData.forEach(function(process, index) {
            console.log('处理工序数据:', process);
            
            // 确保工序数据有正确的字段
            var processId = process.id || process.processId || (index + 1);
            var processCode = process.processCode || process.code || '-';
            var processName = process.processName || process.name || '-';
            var responsibilityName = process.responsibilityName || process.responsibility || '-';
            var departId = process.departId || process.department || '';
            var note = process.note || '';
            
            var row = `
                <tr data-id="${processId}" data-process='${JSON.stringify(process).replace(/'/g, "&apos;")}'>
                    <td class="checkbox-cell">
                        <input type="checkbox" class="process-checkbox" />
                    </td>
                    <td>${index + 1}</td>
                    <td>${index + 1}</td>
                    <td>${processCode}</td>
                    <td>${processName}</td>
                    <td>${responsibilityName}</td>
                    <td>${getDepartmentName(departId)}</td>
                    <td><input type="text" value="${note}" class="process-note-input" placeholder="请输入备注" /></td>
                    <td class="operation-cell">
                        ${index > 0 ? '<a href="javascript:void(0)" class="operation-link-text up-link" onclick="moveProcess(\'' + processId + '\', \'up\')">上移</a>' : ''}
                        ${index < processesData.length - 1 ? '<a href="javascript:void(0)" class="operation-link-text down-link" onclick="moveProcess(\'' + processId + '\', \'down\')">下移</a>' : ''}
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
        
        // 更新全局变量
        processes = processesData.map(function(process, index) {
            return {
                id: process.id || process.processId || (index + 1),
                code: process.processCode || process.code || '',
                name: process.processName || process.name || '',
                responsibility: process.responsibilityName || process.responsibility || '',
                department: getDepartmentName(process.departId || process.department || ''),
                note: process.note || ''
            };
        });
        processCounter = processes.length;
        
        console.log('工序列表显示完成，共', processes.length, '条');
        console.log('更新后的processes数组:', processes);
        console.log('所有工序的真实ID:', processes.map(p => p.id));
    }
    
    // 获取部门名称
    function getDepartmentName(departId) {
        switch(departId) {
            case 1: return '生产部';
            case 2: return '质检部';
            case 3: return '技术部';
            case 4: return '采购部';
            case 5: return '销售部';
            default: return departId || '-';
        }
    }
    
    // 加载状态函数已取消
    
    // 显示错误信息
    function showError(message) {
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.msg(message, {icon: 2, time: 3000});
        });
        
        // 显示错误状态
        $('.main-container').prepend(`
            <div style="margin: 20px; padding: 20px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; color: #721c24;">
                <i class="layui-icon layui-icon-close-fill" style="font-size: 20px; margin-right: 10px;"></i>
                <span>${message}</span>
                <button class="btn btn-primary" onclick="goBack()" style="margin-left: 20px;">返回列表</button>
            </div>
        `);
    }
    
    // 生成工艺编号
    function generateCraftsCode() {
        var randomNum = Math.floor(Math.random() * 9000) + 1000; // 生成1000-9999的随机数
        var craftsCode = 'CRA' + randomNum;
        $('#craftsCode').val(craftsCode);
        console.log('生成新的工艺编号:', craftsCode);
    }
    
    // 切换工艺编号输入模式
    function toggleCraftsCodeInput() {
        var isSystemCode = $('#isSystemCode').is(':checked');
        var craftsCodeInput = $('#craftsCode');
        var refreshBtn = $('#refreshCodeBtn');
        
        if (isSystemCode) {
            // 系统编号模式：自动生成编号，输入框只读
            craftsCodeInput.prop('readonly', true);
            craftsCodeInput.css('background-color', '#f8f9fa');
            craftsCodeInput.css('cursor', 'not-allowed');
            refreshBtn.show(); // 显示刷新按钮
            generateCraftsCode(); // 生成新的编号
            console.log('切换到系统编号模式');
        } else {
            // 手动输入模式：可以手动输入，输入框可编辑
            craftsCodeInput.prop('readonly', false);
            craftsCodeInput.css('background-color', 'white');
            craftsCodeInput.css('cursor', 'text');
            refreshBtn.hide(); // 隐藏刷新按钮
            craftsCodeInput.focus(); // 聚焦到输入框
            console.log('切换到手动输入模式');
        }
    }
    
    // 验证工艺编号格式
    function validateCraftsCode(code) {
        // 允许的格式：字母+数字，长度3-20位
        var pattern = /^[A-Za-z0-9]{3,20}$/;
        return pattern.test(code);
    }
    
    // 工艺编号输入验证
    $('#craftsCode').on('input', function() {
        if (!$('#isSystemCode').is(':checked')) {
            var code = $(this).val();
            if (code && !validateCraftsCode(code)) {
                $(this).css('border-color', '#dc3545');
                $(this).css('box-shadow', '0 0 0 2px rgba(220, 53, 69, 0.1)');
            } else {
                $(this).css('border-color', '#28a745');
                $(this).css('box-shadow', '0 0 0 2px rgba(40, 167, 69, 0.1)');
            }
        }
    });
    
    // 获取工序ID列表，用逗号分隔
    function getProcessesIdList() {
        var idList = [];
        
        // 从processes数组中获取所有工序的真实主键ID
        if (processes && processes.length > 0) {
            processes.forEach(function(process) {
                if (process && process.id) {
                    // 直接使用保存的真实主键ID
                    idList.push(process.id);
                }
            });
        }
        
        // 用逗号连接ID列表
        var result = idList.join(',');
        console.log('获取工序真实主键ID列表:', idList, '结果字符串:', result);
        
        // 如果没有工序，返回空字符串
        if (idList.length === 0) {
            console.warn('警告：没有找到任何工序数据');
            return '';
        }
        
        return result;
    }
    

    




    // 添加工序
    function addProcess(processData) {
        var process = processData || {
            id: 'GJ-' + String(processes.length + 1).padStart(3, '0'),
            code: 'GJ-' + String(processes.length + 1).padStart(3, '0'),
            name: '工序' + (processes.length + 1),
            responsibility: '',
            department: '生产部',
            note: ''
        };
        
        // 确保传入的工序数据有正确的ID（使用真实的主键ID）
        if (processData) {
            // 保持原始的真实ID，不覆盖
            process.id = processData.id; // 直接使用传入的真实ID
            process.code = processData.code || processData.processCode || process.code;
            process.name = processData.name || processData.processName || process.name;
            process.responsibility = processData.responsibility || processData.responsibilityName || process.responsibility;
            process.department = processData.department || process.department;
            process.note = processData.note || process.note;
        }

        console.log('添加工序，工序数据:', process);

        // 计算显示序号（用于界面显示）
        var displayIndex = processes.length + 1;

        var row = `
            <tr data-id="${process.id}" data-process='${JSON.stringify(process).replace(/'/g, "&apos;")}'>
                <td class="checkbox-cell">
                    <input type="checkbox" class="process-checkbox" />
                </td>
                <td>${displayIndex}</td>
                <td>${displayIndex}</td>
                <td>${process.code}</td>
                <td>${process.name}</td>
                <td>${process.responsibility}</td>
                <td>${process.department}</td>
                <td>
                    <input type="text" class="process-note" placeholder="请输入备注" value="${process.note}" />
                </td>
                <td class="operation-cell">
                    ${displayIndex > 1 ? '<a href="javascript:void(0)" class="operation-link primary" onclick="moveProcess(\'' + process.id + '\', \'up\')">上移</a>' : ''}
                    ${displayIndex < (processes.length + 1) ? '<a href="javascript:void(0)" class="operation-link primary" onclick="moveProcess(\'' + process.id + '\', \'down\')">下移</a>' : ''}
                </td>
            </tr>
        `;

        $('#processTableBody').append(row);
        processes.push(process);
        
        // 更新processCounter
        processCounter = processes.length;
        
        console.log('工序添加完成，当前processCounter:', processCounter, 'processes数组:', processes);
        console.log('工序真实ID列表:', processes.map(p => p.id));
    }

    // 移除工序
    function removeProcess() {
        var selectedRows = $('.process-checkbox:checked');
        console.log('选中的工序行数:', selectedRows.length);
        
        if (selectedRows.length === 0) {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg('请选择要移除的工序', {icon: 2, time: 2000});
            });
            return;
        }

        layui.use('layer', function(){
            var layer = layui.layer;
            layer.confirm('确定要移除选中的工序吗？', {
                icon: 3,
                title: '确认移除'
            }, function(index){
                layer.close(index);
                console.log('开始批量移除选中的工序...');
                
                // 收集所有要移除的ID，避免在移除过程中ID变化
                var idsToRemove = [];
                selectedRows.each(function() {
                    var row = $(this).closest('tr');
                    var id = row.data('id');
                    idsToRemove.push(id);
                });
                
                console.log('要移除的工序ID列表:', idsToRemove);
                
                // 按ID从大到小排序，避免移除过程中的索引问题
                idsToRemove.sort((a, b) => b - a);
                console.log('排序后的移除ID列表:', idsToRemove);
                
                // 逐个移除
                idsToRemove.forEach(function(id) {
                    console.log('正在移除工序ID:', id);
                    removeProcessById(id);
                });
                
                // 所有移除完成后，统一更新序号
                console.log('批量移除完成，开始更新序号...');
                updateProcessNumbers();
                
                // 重置全选复选框
                $('#selectAll').prop('checked', false);
            });
        });
    }

    // 根据ID移除工序
    function removeProcessById(id) {
        console.log('开始移除工序ID:', id);
        console.log('移除前processes数组:', processes);
        
        // 移除HTML行
        $(`tr[data-id="${id}"]`).remove();
        
        // 从processes数组中移除对应的工序数据
        processes = processes.filter(p => p.id !== id);
        
        console.log('移除后processes数组:', processes);
        
        // 更新processCounter
        processCounter = processes.length;
        
        console.log('工序已移除，当前processCounter:', processCounter, '剩余工序数:', processes.length);
    }

    // 移除工序行
    function removeProcessRow(id) {
        console.log('单行移除工序，ID:', id);
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.confirm('确定要移除这个工序吗？', {
                icon: 3,
                title: '确认移除'
            }, function(index){
                layer.close(index);
                console.log('确认移除工序ID:', id);
                removeProcessById(id);
            });
        });
    }

    // 移动工序 - 重新设计的移动逻辑
    function moveProcess(id, direction) {
        console.log('=== 开始移动工序 ===');
        console.log('参数 - ID:', id, '方向:', direction);
        
        // 根据当前表格的实际状态查找行
        var rows = $('#processTableBody tr');
        var totalRows = rows.length;
        var targetRow = null;
        var targetIndex = -1;
        
        // 查找目标行
        rows.each(function(index) {
            if ($(this).data('id') == id) {
                targetRow = $(this);
                targetIndex = index;
                return false; // 找到后跳出循环
            }
        });
        
        console.log('查找结果:', {
            totalRows: totalRows,
            targetId: id,
            targetIndex: targetIndex,
            targetRowFound: targetRow !== null
        });
        
        if (!targetRow) {
            console.error('错误：找不到ID为', id, '的行');
            console.log('当前所有行的ID:', rows.map(function() { return $(this).data('id'); }).get());
            return;
        }
        
        // 获取当前行信息
        var currentData = {
            id: targetRow.data('id'),
            seq1: targetRow.find('td:eq(1)').text(),
            seq2: targetRow.find('td:eq(2)').text(),
            code: targetRow.find('td:eq(3)').text(),
            name: targetRow.find('td:eq(4)').text()
        };
        console.log('当前行信息:', currentData);
        
        var moveSuccess = false;
        
        if (direction === 'up' && targetIndex > 0) {
            // 向上移动：与上一行交换位置
            var prevRow = rows.eq(targetIndex - 1);
            var prevData = {
                id: prevRow.data('id'),
                name: prevRow.find('td:eq(4)').text()
            };
            
            console.log('向上移动：将行', currentData.name, '(ID:', currentData.id, ') 移动到行', prevData.name, '(ID:', prevData.id, ') 之前');
            
            // 执行移动
            targetRow.insertBefore(prevRow);
            moveSuccess = true;
            console.log('向上移动成功');
            
        } else if (direction === 'down' && targetIndex < totalRows - 1) {
            // 向下移动：与下一行交换位置
            var nextRow = rows.eq(targetIndex + 1);
            var nextData = {
                id: nextRow.data('id'),
                name: nextRow.find('td:eq(4)').text()
            };
            
            console.log('向下移动：将行', currentData.name, '(ID:', currentData.id, ') 移动到行', nextData.name, '(ID:', nextData.id, ') 之后');
            
            // 执行移动
            targetRow.insertAfter(nextRow);
            moveSuccess = true;
            console.log('向下移动成功');
            
        } else {
            console.log('移动失败：无效的移动方向或位置');
            console.log('direction:', direction, 'targetIndex:', targetIndex, 'totalRows:', totalRows);
            return;
        }
        
        if (moveSuccess) {
            // 移动完成后更新序号和ID
            console.log('移动完成，开始更新序号...');
            updateProcessNumbers();
        }
        
        console.log('=== 移动工序完成 ===');
    }

    // 更新工序序号 - 修复版本
    function updateProcessNumbers() {
        var totalRows = $('#processTableBody tr').length;
        console.log('=== 开始更新工序序号 ===');
        console.log('总行数:', totalRows);
        
        // 重新构建processes数组，确保顺序与表格一致
        var newProcesses = [];
        
        $('#processTableBody tr').each(function(index) {
            var row = $(this);
            var newId = index + 1;
            var oldId = row.data('id');
            
            console.log(`行${index + 1}: 旧ID=${oldId}, 新ID=${newId}`);
            
            // 重要：同时更新data-id属性和attr属性，确保一致性
            row.data('id', newId);
            row.attr('data-id', newId);
            
            // 更新序号列（第2列和第3列）
            row.find('td:eq(1)').text(newId);
            row.find('td:eq(2)').text(newId);
            
            // 收集当前行的工序数据
            var processData = {
                id: newId,
                code: row.find('td:eq(3)').text(),
                name: row.find('td:eq(4)').text(),
                responsibility: row.find('td:eq(5)').text(),
                department: row.find('td:eq(6)').text(),
                note: row.find('td:eq(7) input').val() || ''
            };
            
            newProcesses.push(processData);
            
            // 更新操作按钮 - 确保ID正确
            var operationCell = row.find('td:eq(8)');
            var upButton = newId > 1 ? 
                '<a href="javascript:void(0)" class="operation-link primary" onclick="moveProcess(' + newId + ', \'up\')">上移</a>' : '';
            var downButton = newId < totalRows ? 
                '<a href="javascript:void(0)" class="operation-link primary" onclick="moveProcess(' + newId + ', \'down\')">下移</a>' : '';
            
            // 确保按钮之间有适当的间距
            var buttonHtml = upButton + (upButton && downButton ? ' ' : '') + downButton;
            operationCell.html(buttonHtml);
            
            console.log(`行${newId}: 按钮更新完成 - 上移=${upButton ? '显示' : '隐藏'}, 下移=${downButton ? '显示' : '隐藏'}`);
            console.log(`行${newId}: 按钮HTML=${buttonHtml}`);
        });
        
        // 用新的数组替换旧的processes数组
        processes = newProcesses;
        
        // 更新processCounter
        processCounter = totalRows;
        
        console.log('=== 工序序号更新完成 ===');
        console.log('当前总行数:', totalRows);
        console.log('最终processes数组:', processes);
        console.log('更新后的processCounter:', processCounter);
        
        // 验证更新结果
        console.log('验证更新结果:');
        $('#processTableBody tr').each(function(index) {
            var row = $(this);
            var dataId = row.data('id');
            var attrId = row.attr('data-id');
            var seq1 = row.find('td:eq(1)').text();
            var seq2 = row.find('td:eq(2)').text();
            console.log(`验证行${index + 1}: data-id=${dataId}, attr-data-id=${attrId}, 序号1=${seq1}, 序号2=${seq2}`);
        });
    }

    // 全选/取消全选
    function toggleSelectAll() {
        var isChecked = $('#selectAll').prop('checked');
        $('.process-checkbox').prop('checked', isChecked);
    }

    // 选择负责人
    function selectResponsibility() {
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.msg('选择负责人功能开发中...', {icon: 1});
        });
    }

    // 选择部门
    function selectDepartment() {
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.msg('选择部门功能开发中...', {icon: 1});
        });
    }



    // 保存工艺
    function saveCrafts() {
        // 获取表单数据
        var formData = {
            craftsCode: $('#craftsCode').val(),
            craftsName: $('#craftsName').val(),
            responsibilityName: $('#responsibilityName').val(),
            departId: $('#department').val(),
            craftsStatus: $('input[name="craftsStatus"]:checked').val(),
            note: $('#note').val(),
            pidlist: getProcessesIdList()
        };

        // 表单验证
        if (!formData.craftsName) {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg('请填写工艺流程名称', {icon: 2, time: 2000});
            });
            return;
        }

        console.log('准备保存的工艺数据:', formData);
        console.log('状态值详情:');
        console.log('- 选中的状态值:', formData.craftsStatus);
        console.log('- 状态值类型:', typeof formData.craftsStatus);
        console.log('- 启用按钮值:', $('#craftsStatusEnabled').val());
        console.log('- 禁用按钮值:', $('#craftsStatusDisabled').val());
        console.log('- 当前选中的状态按钮:', $('input[name="craftsStatus"]:checked').attr('id'));
        console.log('工序ID列表详情:');
        console.log('- processes数组:', processes);
        console.log('- 每个工序的ID:', processes.map(p => ({ id: p.id, code: p.code, name: p.name })));
        console.log('- pidlist值:', formData.pidlist);
        console.log('- 工序数量:', processes.length);
        
        // 测试pidlist生成
        var testPidlist = getProcessesIdList();
        console.log('测试生成的pidlist:', testPidlist);
        console.log('pidlist是否匹配:', formData.pidlist === testPidlist);

        // 检查是否为编辑模式
        var urlParams = new URLSearchParams(window.location.search);
        var craftsId = urlParams.get('id');
        
        var apiUrl, successMessage, redirectUrl;
        
        if (craftsId) {
            // 编辑模式
            apiUrl = 'http://localhost:5161/api/Process/CraftsEdit';
            formData.id = craftsId;
            formData.IsUpdOrDel = false; // false表示更新操作
            successMessage = '工艺更新成功';
            redirectUrl = '/Process/Technology';
        } else {
            // 新增模式
            apiUrl = 'http://localhost:5161/api/Process/CraftsAdd';
            successMessage = '工艺添加成功';
            redirectUrl = '/Process/Technology';
        }

        // 显示加载提示
        layui.use('layer', function(){
            var layer = layui.layer;
            var loadIndex = layer.load(1, {shade: [0.3, '#000']});
            
            // 调用保存/更新API
            $.ajax({
                url: apiUrl,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    layer.close(loadIndex);
                    if (res.code === 200) {
                        layer.msg(successMessage, {icon: 1, time: 2000});
                        setTimeout(function() {
                            window.location.href = redirectUrl;
                        }, 2000);
                    } else {
                        layer.msg('操作失败：' + (res.message || '未知错误'), {icon: 2, time: 3000});
                    }
                },
                error: function(xhr, status, error) {
                    layer.close(loadIndex);
                    layer.msg('操作失败：' + error, {icon: 2, time: 3000});
                    console.error('保存/更新工艺失败:', error);
                }
            });
        });
    }

    // 获取工序数据
    function getProcessesData() {
        var processData = [];
        $('#processTableBody tr').each(function() {
            var row = $(this);
            processData.push({
                id: row.data('id'),
                code: row.find('td:eq(3)').text(),
                name: row.find('td:eq(4)').text(),
                responsibility: row.find('td:eq(5)').text(),
                department: row.find('td:eq(6)').text(),
                note: row.find('td:eq(7) input').val()
            });
        });
        return processData;
    }

    // 重置表单
    function resetForm() {
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.confirm('确定要重置表单吗？所有数据将丢失。', {
                icon: 3,
                title: '确认重置',
                btn: ['确定重置', '取消']
            }, function(index) {
                layer.close(index);
                $('#craftsForm')[0].reset();
                $('#processTableBody').empty();
                processCounter = 0;
                processes = [];
            });
        });
    }

    // 返回
    function goBack() {
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.confirm('确定要返回吗？未保存的数据将丢失。', {
                icon: 3,
                title: '确认返回',
                btn: ['确定返回', '取消']
            }, function(index) {
                layer.close(index);
                window.location.href = '/Process/Technology';
            });
        });
    }

    // 工序选择对话框相关变量
    var processSelectTable = null;
    
    // 分页相关变量
    var PageIndex = 1;
    var PageSize = 10;
    var TotalCount = 0;
    var TotalPages = 0;

    // 打开工序选择对话框
    function openProcessDialog() {
        layui.use('layer', function() {
            var layer = layui.layer;
            layer.open({
                type: 1,
                title: '选择工序',
                area: ['1000px', '600px'],
                content: $('#processDialogContent'),
                success: function(layero, index) {
                    // 存储对话框索引
                    window.currentDialogIndex = index;
                    PageIndex = 1;
                    shows();
                },
                end: function() {
                    // 对话框关闭后的清理工作
                    window.currentDialogIndex = null;
                    // 确保对话框内容完全隐藏
                    $('#processDialogContent').hide();
                }
            });
        });
    }

    // 关闭工序选择对话框
    function closeProcessDialog() {
        layui.use('layer', function() {
            var layer = layui.layer;
            if (window.currentDialogIndex !== null) {
                layer.close(window.currentDialogIndex);
            } else {
                layer.closeAll();
            }
        });
    }

    // 重置搜索条件
    function resetSearch() {
        $("#searchProcessCode").val('');
        $("#searchProcessName").val('');
        PageIndex = 1;
        shows();
    }

    // 搜索工序
    function searchProcesses() {
        PageIndex = 1;
        shows();
    }



    // 选择工序
    function selectProcess(processCode, processName, responsibilityName, department) {
        console.log('准备选择工序:', processCode, processName, responsibilityName, department);
        console.log('当前processes数组:', processes);
        
        // 阻止任何可能的表单验证
        event.preventDefault();
        event.stopPropagation();
        
        // 检查是否已存在相同工序编码
        var existingProcess = processes.find(p => p.code === processCode);
        if (existingProcess) {
            console.log('发现重复工序编码:', existingProcess);
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg('该工序已存在，请选择其他工序', {icon: 2, time: 2000});
            });
            return;
        }
        
        // 从工序选择对话框中获取完整的工序数据
        var row = $(event.target).closest('tr');
        var processRowData = row.data('row');
        
        console.log('从data-row获取的工序数据:', processRowData);
        
        // 添加工序到表格，使用真实的主键ID
        var processData = {
            id: processRowData.id, // 直接使用真实的主键ID
            code: processCode,
            name: processName,
            responsibility: responsibilityName,
            department: department,
            note: ''
        };
        
        console.log('添加工序数据:', processData);
        console.log('工序真实ID:', processData.id);
        console.log('准备调用addProcess函数...');
        addProcess(processData);
        
        // 验证添加后的状态
        console.log('addProcess调用完成，当前processes数组:', processes);
        console.log('当前表格行数:', $('#processTableBody tr').length);
        console.log('所有工序的真实ID:', processes.map(p => p.id));
        
        // 关闭对话框
        layui.use('layer', function(){
            var layer = layui.layer;
            if (window.currentDialogIndex !== null) {
                layer.close(window.currentDialogIndex);
            } else {
                layer.closeAll();
            }
        });
        
        // 显示成功提示
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.msg('工序添加成功', {icon: 1, time: 1500});
        });
    }







    // 显示工序列表
    function shows() {
        var ProcessCode = $("#searchProcessCode").val();
        var ProcessName = $("#searchProcessName").val();
        
        $.ajax({
            url: 'http://localhost:5161/api/Process/ProcessDtoQuery',
            type: 'GET',
            data: {
                PageIndex: PageIndex,
                PageSize: PageSize,
                processCode: ProcessCode,
                processName: ProcessName
            },
            async: false,
            success: res => {
                console.log(res);
                TotalCount = res.data.totalCount;
                TotalPages = res.data.totalPages;
                
                $("#tb").empty();
                
                $(res.data.list).each(function() {
                    var displayStatus = this.processStatus === 0 ? "启用" : "禁用";
                    var statusClass = this.processStatus === 0 ? "status-enabled" : "status-disabled";
                    var statusIcon = this.processStatus === 0 ? "layui-icon-ok-circle" : "layui-icon-close-fill";
                    
                    var displayDept = "";
                    if (this.departId === 1) displayDept = "生产部";
                    else if (this.departId === 2) displayDept = "质检部";
                    else if (this.departId === 3) displayDept = "技术部";
                    
                    // 根据状态决定按钮是否可用
                    var isDisabled = this.processStatus === 1; // 1表示禁用
                    var buttonClass = isDisabled ? "layui-btn layui-btn-xs layui-btn-disabled" : "layui-btn layui-btn-xs layui-btn-normal select-btn";
                    var buttonText = isDisabled ? "已禁用" : "选择";
                    var buttonIcon = isDisabled ? "layui-icon-close-fill" : "layui-icon-ok";
                    
                    var row = $('<tr>').attr('data-row', JSON.stringify(this).replace(/'/g, "&apos;"));
                    row.append(`
                        <td><span class="process-code">${this.processCode}</span></td>
                        <td><span class="process-name">${this.processName}</span></td>
                        <td><span class="process-type">${this.ptName}</span></td>
                        <td><span class="process-responsible">${this.responsibilityName}</span></td>
                        <td><span class="status-badge ${statusClass}"><i class="layui-icon ${statusIcon}"></i> ${displayStatus}</span></td>
                        <td><span class="process-dept">${displayDept}</span></td>
                        <td><span class="process-note">${this.note || '-'}</span></td>
                        <td>
                            <button class="${buttonClass}" type="button" ${isDisabled ? 'disabled' : ''}>
                                <i class="layui-icon ${buttonIcon}"></i> ${buttonText}
                            </button>
                        </td>
                    `);
                    
                    // 使用事件委托绑定点击事件，避免onclick属性可能的问题
                    if (!isDisabled) {
                        row.find('button').on('click', function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            selectProcess(this.processCode, this.processName, this.responsibilityName, this.displayDept);
                        }.bind({
                            processCode: this.processCode,
                            processName: this.processName,
                            responsibilityName: this.responsibilityName,
                            displayDept: displayDept
                        }));
                    }
                    
                    $("#tb").append(row);
                });
                
                renderPagination();
            }
        });
    }

    // 渲染分页
    function renderPagination() {
        layui.use(function() {
            var laypage = layui.laypage;
            
            laypage.render({
                elem: 'demo-laypage-all',
                count: TotalCount,
                limit: PageSize,
                curr: PageIndex,
                limits: [5, 10, 15, 20],
                layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                jump: function(obj, first) {
                    if (!first) {
                        PageIndex = obj.curr;
                        PageSize = obj.limit;
                        shows();
                    }
                }
            });
        });
    }




    
</script>
